//
//  ZLDetailViewController.m
//  TripTogether
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 杨泓晔. All rights reserved.
//

#import "ZLDetailViewController.h"
#import "ZLDetailHeaderReusableView.h"
#import "ZLDetailFooterReusableView.h"
#import "WJQNetwork.h"
#import "ZLDetailCollectionViewCell.h"
#import "ZLDetailImageModel.h"
#import "ZLHeaderImageModel.h"
#import "ZLTapViewController.h"
#import "ZLImpressViewController.h"
#import "ZLHootViewController.h"




@interface ZLDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,ZLDetailFooterReusableViewDelegate>

@property (nonatomic, strong)NSMutableArray *myArray;
@property (nonatomic, strong)UICollectionView *myCollectionView;
@property (nonatomic, strong)NSMutableArray *imageArray;

@property (nonatomic, strong)UIImageView *myImageView;

//@property (nonatomic, strong)ZLHeaderImageModel *headerImageM;

@property (nonatomic, strong)UILabel *nameLabel;

@property (nonatomic, strong)UILabel *myLabel;


@property (nonatomic, strong)UIView *navCView;

@end

@implementation ZLDetailViewController
#pragma mark - 隐藏tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *view = temp[2];
    view.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.96 blue:0.91 alpha:1];
//    NSLog(@"%@",self.zlDataM.myId);
    self.myArray = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];
    [self setAutomaticallyAdjustsScrollViewInsets:YES];
    [self createCollectionView];
    [self MBShow];
    
    [self getImageData];

}

#pragma mark - 创建CollectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.sectionInset = UIEdgeInsetsMake(5*AUTO_HEIGHT, 10*AUTO_WIDTH, 10*AUTO_HEIGHT, 10*AUTO_WIDTH);
    //行 列 间距
    flowLayout.minimumLineSpacing = 5*AUTO_HEIGHT;
    flowLayout.minimumInteritemSpacing = 5*AUTO_WIDTH;
    
    self.myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flowLayout];
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    self.myCollectionView.backgroundColor = [UIColor colorWithRed:0.98 green:0.96 blue:0.91 alpha:1];
    [self.view addSubview:self.myCollectionView];
    
    //******************
    self.myCollectionView.contentInset = UIEdgeInsetsMake(240*AUTO_HEIGHT, 0, 0, 0);
    [self getHeaderImage];
    [self createHeaderImage];
    
    
    //注册
    [self.myCollectionView registerClass:[ZLDetailCollectionViewCell class] forCellWithReuseIdentifier:@"ZLDetailCollectionViewCell"];
    
    [self.myCollectionView registerClass:[ZLDetailHeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ZLDetailHeaderReusableView"];
    
    [self.myCollectionView registerClass:[ZLDetailFooterReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"ZLDetailFooterReusableView"];
    
#pragma mark - navigationController透明实现
    self.navCView = [[UIView alloc]init];
    [self.view addSubview:self.navCView];
    self.navCView.backgroundColor = [UIColor colorWithRed:0.33 green:0.74 blue:0.8 alpha:1];
    self.navCView.alpha = 0;
    [self.navCView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.equalTo(self.view);
        make.height.equalTo(@64);
    }];
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn setImage:[UIImage imageNamed:@"icon_nav_back_button@2x.png"] forState:(UIControlStateNormal)];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.top.equalTo(self.navCView.mas_top).offset(15);
        make.height.equalTo(@49);
        make.width.equalTo(@30);
    }];
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UILabel *label = [[UILabel alloc]init];
    [self.navCView addSubview:label];
    label.text = self.zlDataM.name;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"Gurmukhi MN" size:20.0f];
    label.textAlignment = NSTextAlignmentCenter;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view.mas_left).offset(120);
        make.right.equalTo(self.view.mas_right).offset(-120);
        make.height.equalTo(@49);
        make.top.equalTo(self.navCView.mas_top).offset(15);
    }];
    
    
}

#pragma mark - 头视图创建
- (void)createHeaderImage
{
    self.myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -240*AUTO_HEIGHT, SCREEN_WIDTH, 240*AUTO_HEIGHT)];
//    self.myImageView.backgroundColor = [UIColor purpleColor];
    self.myImageView.userInteractionEnabled = YES;
#warning 设置myImageView高度改变时 宽度也跟着变化
    self.myImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    [self.myCollectionView addSubview:self.myImageView];
//    [self.myImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(self.view);
//        make.top.equalTo(self).offset(-180);
//        make.height.equalTo(@180);
//    }];
    self.nameLabel = [UILabel new];
    self.nameLabel.font = [UIFont fontWithName:@"Gurmukhi MN" size:25.0f];
    self.nameLabel.textColor = [UIColor whiteColor];
    [self.myImageView addSubview:self.nameLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.myImageView addGestureRecognizer:tap];

    
//    self.nameLabel.backgroundColor = [UIColor grayColor];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.myImageView.mas_left).offset(20);
        make.bottom.equalTo(self.myImageView.mas_bottom).offset(-60);
        make.width.equalTo(@(220*AUTO_WIDTH));
        make.height.equalTo(@(50*AUTO_HEIGHT));
    }];
    
    self.myLabel = [[UILabel alloc]init];
    self.myLabel.font = [UIFont fontWithName:@"Apple SD Gothic Neo" size:14.0f];
    self.myLabel.textColor = [UIColor whiteColor];
//    self.myLabel.backgroundColor = [UIColor yellowColor];
    [self.myImageView addSubview:self.myLabel];
    [self.myLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    
        make.left.equalTo(self.myImageView.mas_left).offset(20);
        make.width.equalTo(@220);
        make.bottom.equalTo(self.myImageView).offset(-40);
        make.height.equalTo(@20);
    }];
    

 
}

#pragma mark - 轻拍头视图
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    ZLTapViewController *zlTapVC = [[ZLTapViewController alloc]init];
    zlTapVC.string = self.nameLabel.text;
    zlTapVC.type = self.zlDataM.type;
    zlTapVC.myId = self.zlDataM.myId;
     [self.navigationController pushViewController:zlTapVC animated:YES];
    
}


#pragma mark - CollectionView协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.myArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZLDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZLDetailCollectionViewCell" forIndexPath:indexPath];
    
        ZLDetailImageModel *detailImageM = [self.myArray objectAtIndex:indexPath.row];
        cell.zlDetailImageM = detailImageM;
        return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZLImpressViewController *impressVC = [ZLImpressViewController new];
    
    ZLDetailImageModel *zlDetailImageM = [self.myArray objectAtIndex:indexPath.row];
    impressVC.type = zlDetailImageM.type;
    impressVC.myId = zlDetailImageM.myId;
    impressVC.headerImage = zlDetailImageM.cover;
    impressVC.name = zlDetailImageM.name;
    impressVC.lat = zlDetailImageM.zlLocationM.lat;
    impressVC.lng = zlDetailImageM.zlLocationM.lng;
    [self.navigationController pushViewController:impressVC animated:YES];
}

#pragma mark - item高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH - 27*AUTO_WIDTH)/2, (SCREEN_WIDTH - 25*AUTO_WIDTH)/2);
}

#pragma mark - 首部 尾部
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        ZLDetailHeaderReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ZLDetailHeaderReusableView" forIndexPath:indexPath];
        
        reusableView.layer.masksToBounds = YES;
        reusableView.layer.cornerRadius = 8;
        
        return reusableView;
        
    }else{
        ZLDetailFooterReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"ZLDetailFooterReusableView" forIndexPath:indexPath];
        reusableView.detailFooterReusableViewDelegate = self;
        
        if (indexPath.row < 6) {
            return reusableView;
        }else{
            return nil;
        }
        
    }
}

//首部高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 30);
}

//尾部高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (self.myArray.count < 6) {
        return CGSizeZero;
    }else{
        return CGSizeMake(SCREEN_WIDTH, 50);
        
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //刚开始y的偏移量初始值就是-260;
    self.myImageView.layer.masksToBounds = YES;
//    NSLog(@"iiiiii%f",scrollView.contentOffset.y);
    CGFloat y = self.myCollectionView.contentOffset.y;
    
    self.navCView.alpha =1.0 - (-y/260*AUTO_HEIGHT);
    
    
    if (y < -240*AUTO_HEIGHT) {
        
        CGRect frame = self.myImageView.frame;
        frame.origin.y = y;//偏移了多少
        frame.size.height = -y;//CollectionView向下偏移了多少,高度就是多少
        self.myImageView.frame = frame;
    }
//    else{
//        self.myImageView.layer.masksToBounds = NO;
//        CGRect f = self.myImageView.frame;
//        f.origin.y = 0;
//        self.myImageView.frame = CGRectMake(0, -240*AUTO_HEIGHT, SCREEN_WIDTH, 240*AUTO_HEIGHT);
//    }
    
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.myCollectionView.contentOffset.y < -400*AUTO_HEIGHT) {
        ZLTapViewController *zlTapVC = [[ZLTapViewController alloc]init];
        zlTapVC.string = self.nameLabel.text;
        zlTapVC.type = self.zlDataM.type;
        zlTapVC.myId = self.zlDataM.myId;
        [self.navigationController pushViewController:zlTapVC animated:YES];
    }
}

- (void)btnAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark - 请求数据
- (void)getImageData
{
    //http://api.breadtrip.com/destination/place/2/6636/pois/all/?sort=default&start=0&latitude=38.883499&longitude=121.544943&sign=a4661007f088a14d6dcd37eddd67b078
    
    //http://api.breadtrip.com/destination/place/2/7559/pois/all/?sort=default&start=0&latitude=38.883513&longitude=121.544840&sign=8cdb02b56882cf1d0482e2f5477fbaed
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/pois/all/?sort=default",self.zlDataM.type,self.zlDataM.myId];
    [WJQNetwork getAFNet:urlStr block:^(id result) {
        NSMutableDictionary *Dic = result;
        NSMutableArray *itemsArr = [Dic objectForKey:@"items"];
        for (NSMutableDictionary *dic in itemsArr) {
            ZLDetailImageModel *zlDetailImageM = [ZLDetailImageModel new];
            [zlDetailImageM setValuesForKeysWithDictionary:dic];
            
            if (self.myArray.count < 6) {
                [self.myArray addObject:zlDetailImageM];
            }else{
                continue;
            }
        }
        [self MBHide];
        [self.myCollectionView reloadData];
        
    } errorBlock:^(NSError *error) {
        
        NSLog(@"请求失败");
    }];
}

- (void)getHeaderImage
{
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/",self.zlDataM.type,self.zlDataM.myId];
    [WJQNetwork getAFNet:str block:^(id result) {
       
        NSMutableDictionary *dic = result;
        ZLHeaderImageModel *headerM = [ZLHeaderImageModel new];
        [headerM setValuesForKeysWithDictionary:dic];
        [self.myImageView sd_setImageWithURL:[NSURL URLWithString:[[headerM  shareImageM] imageModel].shr_image] placeholderImage:PICHOLDEER];
        self.nameLabel.text = headerM.name;
        
        NSString *str = [NSString stringWithFormat:@"%ld去过/",headerM.visited_count];
        NSString *string = [NSString stringWithFormat:@"%ld喜欢",headerM.wish_to_go_count];
        self.myLabel.text = [str stringByAppendingString:string];
        
        
        
       
    } errorBlock:^(NSError *error) {
        
        NSLog(@"请求失败");
    }];
}

#pragma mark - 全部热门地点 方法实现
- (void)toDestinationDetailIntroduce
{
    ZLHootViewController *zlhotVC = [ZLHootViewController new];
    zlhotVC.zlDataM = self.zlDataM;
    [self.navigationController pushViewController:zlhotVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
